<template>
  <view class="container">
    <!-- <view class="back_img">
	  	 <image class="image" src="/static/images/qpbc.png" mode="widthFix"></image>
	  </view> -->
    <view class="wechatapp">
      <!-- <view class="header">
        <image class="image" :src="imgurl+loginBackdropImg" mode="widthFix"></image>
      </view> -->
      <!-- 中信国安“安全生产月”线上答题活动 -->
      <view class="logoname1"> 中信国安 </view>
      <view class="logoname"> “安全生产月” </view>
      <view class="logoname-js"> 线上答题活动 </view>
    </view>

    <!-- <view class="auth-phonetitle" v-if="form.longinType==2">请输入您的账号密码登录</view>
	<view class="auth-phonetitle" v-if="form.longinType==1">
		请输入您的手机号登录
	</view> -->
    <!-- <view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view> -->
    <view class="login-view">
      <u-form :model="form" ref="uForm" labelWidth="0">
        <u-form-item
          v-if="form.longinType == 1"
          label="+86"
          labelWidth="130"
          prop="mobile"
          :label-style="{ 'font-size': '30rpx', 'font-weight': 'bold' }"
        >
          <view class="item-phone">
            <u-icon name="arrow-down-fill" size="23" class="icon-cone"></u-icon>
            <u-input
              v-model="form.mobile"
              placeholder="请输入手机号"
              :custom-style="{ 'font-size': '30rpx' }"
            />
          </view>
        </u-form-item>
        <!-- <view class="tsshow" v-if="form.longinType == 1">
          未注册的手机号验证后自动创建账户
        </view> -->
        <u-form-item
          label-width="20"
          v-if="form.longinType == 2"
          label=" "
          prop="userCode"
          :label-style="{ 'font-size': '30rpx', 'font-weight': 'bold' }"
        >
          <u-input
            v-model="form.userCode"
            placeholder="请输入账号"
            :custom-style="{ 'font-size': '30rpx' }"
          />
        </u-form-item>
        <u-form-item
          v-if="form.longinType == 2"
          label-width="20"
          label=" "
          prop="password"
          :label-style="{ 'font-size': '30rpx', 'font-weight': 'bold' }"
        >
          <u-input
            v-model="form.password"
            type="password"
            :adjust-position="false"
            placeholder="请输入密码"
            :custom-style="{ 'font-size': '30rpx' }"
          />
        </u-form-item>
        <u-form-item
          v-if="form.longinType == 1"
          label-width="20"
          label=" "
          prop="smsCode"
          :label-style="{ 'font-size': '30rpx', 'font-weight': 'bold' }"
        >
          <view class="item-yzm">
            <u-input
              v-model="form.smsCode"
              type="number"
              placeholder="手机验证码"
              :custom-style="{ 'font-size': '30rpx', width: '350rpx' }"
            />
            <u-button
              v-if="form.longinType == 1"
              :custom-style="{
                width: '100%',
                background: '#ffffff',
                color: '#bc040c',
                border: 'none',
                height: '99rpx',
              }"
              shape="circle"
              @click="gocode"
              :disabled="disabled"
              class="button btn-normal"
              >{{ bttest }}</u-button
            >
          </view>
        </u-form-item>
      </u-form>
    </view>

    <view class="login-btn">
      <!-- @click="gocode"  disabled="disabled"-->
      <!-- <u-button class="btstyle"   :custom-style="{'width':'165rpx','background': '#0065ff','color':'white','border':'none'}" :></u-button> -->
      <!-- <u-button
        v-if="form.longinType == 1 && !isfs"
        :custom-style="{
          width: '100%',
          background: '#ffffff',
          color: '#1B77FB',
          border: 'none',
          height: '99rpx',
        }"
        shape="circle"
        @click="gocode"
        :disabled="disabled"
        class="button btn-normal"
        >{{ bttest }}</u-button
      > -->
      <u-button
        v-if="form.longinType == 2"
        :custom-style="{
          width: '100%',
          background: '#d49b7c',
          color: '#1B77FB',
          border: 'none',
          height: '99rpx',
        }"
        shape="circle"
        @click="goregister"
        class="button btn-normal"
        >登录</u-button
      >
      <u-button
        v-if="form.longinType == 1"
        :custom-style="{
          width: '100%',
          background: '#d49b7c',
          color: '#ffffff',
          border: 'none',
          height: '99rpx',
        }"
        shape="circle"
        @click="goregister"
        class="button btn-normal"
        >登录</u-button
      >
    </view>
    <!-- <view class="login-btn-qk">
      <text @click="qhloginfun">{{
        form.longinType == 1 ? '密码登录' : '手机号登录'
      }}</text>
    </view> -->
  </view>
</template>

<script>
import { sendUserCode, userLogin } from '@/api/login/login'
import { BASE_URL_IMAHE } from '../../../utils/https'
const app = getApp()
export default {
  data() {
    return {
      value: false,
      // 商城基本信息
      storeInfo: undefined,
      // 微信小程序登录凭证 (code)
      // 提交到后端，用于换取openid
      imgurl: BASE_URL_IMAHE,
      code: '',
      loginBackdropImg: '',
      form: {
        longinType: 1,
        mobile: '',
        smsCode: '',
        password: '',
        userCode: '',
        token: '',
      },
      list: [
        {
          name: '注册',
          checked: false,
          disabled: false,
        },
      ],
      bttest: '获取短信验证码',
      disabled: false,
      times: 60,
      //定时器
      intetime: null,
      isfs: false,
      mobile: '',
      rules: {
        // 字段名称
        mobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['change', 'blur'],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return this.$u.test.mobile(value)
            },
            message: '手机号码不正确',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur'],
          },
        ],
        smsCode: [
          {
            required: true,
            message: '请输入验证码',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur'],
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur'],
          },
        ],
        userCode: [
          {
            required: true,
            message: '请输入账号',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur'],
          },
        ],
      },
    }
  },

  created() {},
  beforeDestroy() {
    console.log('返回了')
    clearInterval(this.intetime)
    if (!uni.getStorageSync('userId')) {
      uni.removeStorageSync('userId')
      uni.removeStorageSync('mobile')
    }
  },
  onLoad() {
    this.loginBackdropImg = uni.getStorageSync('loginBackdropImg')
      ? uni.getStorageSync('loginBackdropImg')
      : ''
    var sjs = this.randomWord()
    var datatime = Date.parse(new Date())
    var tokens = '' + sjs + '' + datatime
    this.form.token = tokens
    this.form.v = uni.getStorageSync('v')
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules)
  },
  methods: {
    qhloginfun() {
      if (this.form.longinType == 1) {
        uni.navigateTo({
          url: '/pages/empower/login?type=2',
        })
        // this.form.longinType=2
      } else {
        uni.navigateTo({
          url: '/pages/empower/login?type=1',
        })
      }
      uni.setStorageSync('longinType', this.form.longinType)
    },
    randomWord() {
      var chars = [
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
        'i',
        'j',
        'k',
        'l',
        'm',
        'n',
        'o',
        'p',
        'q',
        'r',
        's',
        't',
        'u',
        'v',
        'w',
        'x',
        'y',
        'z',
      ]
      var nums = ''
      for (var i = 0; i < 20; i++) {
        var id = parseInt(Math.random() * 61)
        nums += chars[id]
      }
      return nums
    },
    async goregister() {
      // code:'',
      // password:'',
      // againPassword:'',
      let tjshow = true

      this.$refs.uForm.validate((valid) => {
        if (valid) {
          tjshow = true
        } else {
          tjshow = false
        }
      })

      if (!tjshow) {
        return
      }
      var formdata = {}

      if (this.form.longinType == 1) {
        formdata.longinType = this.form.longinType
        formdata.mobile = this.form.mobile
        formdata.smsCode = this.form.smsCode
        formdata.token = this.form.token
      } else {
        formdata.longinType = this.form.longinType
        formdata.userCode = this.form.userCode
        formdata.password = this.form.password
        formdata.token = this.form.token
      }

      // #ifdef MP-WEIXIN
      formdata.v = uni.getStorageSync('v')
      // #endif
      let Registe = await userLogin(JSON.stringify(formdata))
      if (Registe.result == 0) {
        uni.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 2000,
        })
        let that = this
        // uni.setStorageSync("userId",Registe.user.id)
        if (this.form.longinType == 1) {
          uni.setStorageSync('userMobile', Registe.user.userMobile)
          uni.setStorageSync('userRef', Registe.user.userRef)
          uni.setStorageSync('userCode', Registe.user.userName)
          uni.setStorageSync('userOffice', Registe.user.userOffice)
          uni.setStorageSync('userId', Registe.user.id)
        } else {
          uni.setStorageSync('userMobile', Registe.user.userCode)
          uni.setStorageSync('userRef', Registe.user.userRef)
          uni.setStorageSync('userCode', Registe.user.userName)
          uni.setStorageSync('userOffice', Registe.user.userOffice)
          uni.setStorageSync('userId', Registe.user.id)
        }

        // #ifdef MP-WEIXIN
        console.log('vvvvvvvvvv')
        uni.setStorageSync('v', Registe.v)
        console.log(uni.getStorageSync('v'), 'vvvvvvvvvv')
        // #endif

        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/home/index',
          })
        }, 1500)
      } else {
        var sjs = this.randomWord()
        var datatime = Date.parse(new Date())
        var tokens = '' + sjs + '' + datatime
        this.form.token = tokens
        uni.showToast({
          icon: 'none',
          title: Registe.message,
        })
      }
    },
    async gocode() {
      console.log(1111)
      let that = this
      if (this.form.mobile == '') {
        uni.showToast({
          icon: 'none',
          title: '请填写手机号',
        })
        return
      }
      var data = {
        mobile: this.form.mobile,
      }

      let Code = await sendUserCode(JSON.stringify(data))

      if (Code.result == 0) {
        // setTimeout(() => {
        //   uni.navigateTo({
        //     url: '/pages/empower/login?type=1&phone=' + this.form.mobile,
        //   })
        // }, 1500)

        this.isfs = true
        this.bttest = '60s重新获取'
        this.disabled = true
        that.times = 60
        that.intetime = setInterval(() => {
          that.times = that.times - 1
          that.bttest = that.times + 's重新获取'
          console.log(that.times)

          if (that.times <= 0) {
            this.isfs = false
            clearInterval(that.intetime)
            this.disabled = false
            this.bttest = '获取验证码'
          }
        }, 1000)
        uni.showToast({
          icon: 'none',
          title: '验证码发送成功',
        })
      } else {
        uni.showToast({
          icon: 'none',
          title: Code.message,
        })
      }
    },
    // 选中某个复选框时，由checkbox时触发
    checkboxChange(e) {
      console.log(e, '123')
      this.value = e.value
      console.log(this.value, 'value')
    },
    // 选中任一checkbox时，由checkbox-group触发
    checkboxGroupChange(e) {
      console.log(e, '345')
    },

    //用户登录凭证code
    getCode() {
      const than = this
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: (res) => {
            console.log(res.code, 'res code')
            resolve(res.code)
          },
          fail: reject,
        })
      })
    },

    async getPhoneNumber(e) {
      console.log(e, 'eee')
      console.log(e.detail.code, 'e 手机code')
      const code = await this.getCode()
      console.log(code, '登录用得code')
      const app = this
      if (e.detail.code) {
        const data = {
          phoneCode: e.detail.code,
          wxOpenIdCode: code,
          parentInviteCode: uni.getStorageSync('parentInviteCode') || '',
        }
        //登录接口
        const logoData = await wxLoginApi(data)
        console.log(logoData, '提交到后端登录接口')
        if (logoData.code === 0) {
          uni.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 2000,
          })
          // 获取到的当前数据存入缓存
          const { wxToken, openId, userInfo } = logoData.data
          uni.setStorageSync('token', wxToken)
          uni.setStorageSync('openId', userInfo.wxOpenid)
          uni.setStorageSync('userInfoServer', userInfo)
          uni.setStorageSync('phoneNumber', userInfo.phone)
          uni.setStorageSync('userId', userInfo.userId)
          setTimeout(() => {
            app.handleCancel()
          }, 1500)
        } else {
          uni.showToast({
            title: '登录失败',
            icon: 'success',
            duration: 2000,
          })
          setTimeout(() => {
            app.handleCancel()
          }, 1500)
        }
      }
    },

    // getUserProfile() {
    //   uni.showLoading({
    //     title: "加载中...",
    //   });
    //   //获取用户信息 包含appid
    //   // const appid = uni.getAccountInfoSync();
    //   // console.log(appid, "appid");
    //   const app = this;
    //   console.log("登录授权开始");
    //   wx.canIUse("getUserProfile") &&
    //     wx.getUserProfile({
    //       lang: "zh_CN",
    //       desc: "获取用户相关信息",
    //       async success(res) {
    //         console.log("用户同意了授权");
    //         console.log("用户信息:", res);
    //         // const { encryptedData, iv } = res;
    //         const {
    //           gender,
    //           avatarUrl,
    //           city,
    //           country,
    //           language,
    //           nickName,
    //           province,
    //         } = res.userInfo;
    //         uni.setStorageSync("MyUserInfo", res.userInfo);
    //         // const code = await app.getCode();
    //         uni.login({
    //           provider: "weixin",
    //           success: async (codeData) => {
    //             // app.data.encryptedData = encryptedData;
    //             // app.data.iv = iv;
    //             const data = {
    //               code: codeData.code,
    //               // wxEncryptInfo: {
    //               //   encryptedData: app.trimAll(encryptedData),
    //               //   iv,
    //               // },
    //               memberInfo: {
    //                 avatarUrl: avatarUrl || "",
    //                 city: city || "",
    //                 country: country || "",
    //                 gender: gender || "",
    //                 language: language || "",
    //                 nickName: nickName || "",
    //                 province: province || "",
    //               },
    //               parentInviteCode: uni.getStorageSync("parentInviteCode") || "",
    //             };
    //             //登录接口
    //             const logoData = await getLogin(data);
    //             console.log(logoData, "提交到后端登录接口");
    //             if (logoData.code === 0) {
    //               uni.hideLoading();
    //               uni.showToast({
    //                 title: "登录成功",
    //                 icon: "success",
    //                 duration: 2000,
    //               });
    //               // 获取到的当前数据存入缓存
    //               const { wxToken, openId, userInfo } = logoData.data;
    //               uni.setStorageSync("token", wxToken);
    //               uni.setStorageSync("openId", userInfo.wxOpenid);
    //               uni.setStorageSync("userInfoServer", userInfo);
    //               uni.setStorageSync("phoneNumber", userInfo.phone);
    //               uni.setStorageSync("userId", userInfo.userId);
    //               setTimeout(() => {
    //                 app.handleCancel();
    //               }, 1500);
    //               return true;
    //             } else {
    //               uni.showToast({
    //                 title: "登录失败",
    //                 icon: "success",
    //                 duration: 2000,
    //               });
    //               setTimeout(() => {
    //                 app.handleCancel();
    //               }, 1500);
    //             }
    //           },
    //           fail: (err) => {
    //             console.log(err, "登录错误");
    //           },
    //         });
    //       },
    //       fail() {
    //         console.log("用户拒绝了授权");
    //       },
    //     });
    // },

    // async getPhoneNumber(e) {
    //   console.log(e,'eee')
    //   console.log(e.detail.code, "e 手机code");
    //   const code=await this.getCode()
    //   console.log(code,'登录用得code')
    //   //这里获取code
    //   return;
    //   if (e.detail.code) {
    //     //获取手机号
    //     const getPhoneData = await getPhone(e.detail.code);
    //     if (getPhoneData.code === 0) {
    //       const { phoneNumber } = getPhoneData.data.phone_info;
    //       uni.setStorageSync("phoneNumber", phoneNumber);
    //       uni.showToast({
    //         title: "授权成功",
    //         icon: "success",
    //         duration: 2000,
    //       });
    //       setTimeout(() => {
    //         this.handleCancel();
    //       }, 1500);
    //     } else {
    //       uni.showToast({
    //         title: "授权失败",
    //         icon: "error",
    //         duration: 2000,
    //       });
    //     }
    //   }
    // },

    /**
     * 暂不登录
     */
    handleCancel() {
      // 跳转回原页面
      uni.navigateBack({
        delta: 1,
      })
    },

    /**
     * 登录成功-跳转回原页面
     */
    // onNavigateBack(delta = 1) {
    //   const pages = getCurrentPages();
    //   if (pages.length > 1) {
    //     uni.navigateBack({
    //       delta: Number(delta || 1),
    //     });
    //   } else {
    //     uni.navigateBack({
    //       delta: 1,
    //     });
    //   }
    // },
  },
}
</script>

<style lang="scss" scoped>
.btstyle {
  width: 165rpx;
  background: #0065ff;
  color: white;
}
u-checkbox-group::v-deep {
  .u-checkbox__label {
    margin-right: rpx(0);
  }
}
.icon-cone {
  margin-right: 10rpx;
}

.checkBox_wrapper {
  font-size: rpx(12);
  display: flex;
}

.container {
  padding: 0 0rpx;
  font-size: 32rpx;
  background: #fff;
  min-height: 100vh;
  position: relative;
  background: url('../../static/images/loginbc.png') no-repeat;
  background-size: 750rpx auto;
}
.back_img {
  position: absolute;
  top: 80rpx;
  right: 0rpx;
  z-index: 1;
  image {
    width: 350rpx;
  }
}
.login-test {
  margin-top: rpx(20);

  display: flex;
  justify-content: center;
  .login-item {
    width: rpx(80);
    height: rpx(80);
    text-align: center;
    margin-left: rpx(20);
    margin-right: rpx(20);
    .login-text {
      width: 100%;
      font-size: rpx(15);
      line-height: rpx(35);
    }
    .logoname-js {
      font-weight: 400;
      font-size: 28rpx;
      color: #ffffff;
      line-height: 36rpx;
    }
    .login-icom {
      // width: rpx(48);
      // height: rpx(48);
      // border-radius: 50%;
      // border: rpx(3) solid black;
      // margin: 0 auto;
      .login-icoms {
      }
    }
  }
}
.tsshow {
  font-weight: 500;
  font-size: 26rpx;
  color: #97c1fd;
  line-height: 39rpx;
  padding-top: 39rpx;
  padding-bottom: 56rpx;
  text-align: center;
}
.wechatapp {
  //border-bottom: 1rpx solid #e3e3e3;
  // margin-bottom: 72rpx;

  text-align: left;
  width: 100%;
  overflow: hidden;
  font-weight: 600;
  font-size: 75rpx;
  color: #c80404;
  padding-bottom: 40rpx;
  line-height: 78rpx;
  .logoname1 {
    margin-top: 128rpx;
    // padding-left: 71rpx;
    text-align: center;
  }
  .logoname {
    text-align: center;
  }
  .logoname-js {
    font-weight: 400;
    font-size: 34rpx;
    color: #c80404;
    line-height: 36rpx;
    text-align: center;
    margin-top: 30rpx;
    font-weight: bold;
  }

  .header {
    width: 100%;
    height: 100%;

    .image {
      width: 100%;
      height: 100%;
    }
  }
}

.auth-title {
  color: #585858;
  font-size: 60rpx;
  margin-bottom: 40rpx;
  margin-left: 40rpx;
  margin-top: 80rpx;
}

.auth-phonetitle {
  color: #585858;
  font-size: 30rpx;
  margin-bottom: 40rpx;
  margin-left: 40rpx;
  line-height: 60rpx;
  margin-top: 80rpx;
}

.auth-subtitle {
  color: #888;
  margin-bottom: 88rpx;
  font-size: 60rpx;
}
.login-view {
  width: 100%;
  box-sizing: border-box;
  padding: 0 rpx(20);
  padding-top: 300rpx;
}
.login-btn-qk {
  font-size: 30rpx;
  text-align: center;
  margin-right: 40rpx;
  margin-top: 40rpx;
  font-weight: 500;
  font-size: 28rpx;
  color: #ffffff;
  line-height: 41rpx;
}

.login-btn {
  //padding: 0 20rpx;
  box-sizing: border-box;
  padding: 0 rpx(20);
  margin-bottom: rpx(13);
  margin-top: rpx(13);

  .button {
    height: 88rpx;
    //background: #04be01;
    color: #fff;
    // background: #0065ff;
    font-size: 30rpx;
    // border-radius: rpx(5);
    font-weight: bold;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.no-login-btn {
  box-sizing: border-box;
  padding: 0 rpx(20);
  margin-top: 20rpx;
  //padding: 0 20rpx;

  .button {
    height: 88rpx;
    background: #dfdfdf;
    color: #fff;
    font-size: 30rpx;
    // border-radius: rpx(5);
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.item-phone {
  display: flex;
  align-items: center;
}
.item-yzm {
  width: 100%;
  display: flex;
  align-items: center;
}
::v-deep .u-form-item__body {
  background-color: #ffffff;
  border-radius: z0rpx;
  height: 99rpx;
  overflow: hidden;
}
::v-deep .u-form-item--left__content__label {
  margin-left: 50rpx;
}
::v-deep .u-border-bottom:after {
  border: none;
}
::v-deep input:-internal-autofill-selected {
  background-color: none;
}
::v-deep .u-flex {
  margin-right: 30rpx;
}
</style>
